如何使用 XmlSerializer 反序列化大型文档中的节点

How to deserialize a node in a large document using XmlSerializer

我有一个很大的 XML 文档,我已经将其加载到 XmlDocument 中,我想使用 XmlSerializer class 将选定的元素从中反序列化为.NET class 使用 xsd.exe.

生成

这是我迄今为止尝试过的 MCVE; xsd 和生成的 class 在 post 的末尾。如代码中的注释所述,我得到一个 InvalidOperationException - <Cars xmlns:'http://MyNamespace' /> was not expected:

static string XmlContent = @"
    <RootNode xmlns=""http://MyNamespace"">
        <Cars>
        <Car make=""Volkswagen"" />
        <Car make=""Ford"" />
        <Car make=""Opel"" />
        </Cars>
    </RootNode>";

static void TestMcve()
{
    var doc = new XmlDocument();
    doc.LoadXml(XmlContent);
    var nsMgr = new XmlNamespaceManager(doc.NameTable);
    nsMgr.AddNamespace("myns", "http://MyNamespace");
    var rootSerializer = new XmlSerializer(typeof(RootNode));
    var root = (RootNode) rootSerializer.Deserialize(new XmlNodeReader(doc));
    Console.WriteLine(root.Cars[0].make); // Works fine so far

    var node = doc.DocumentElement.SelectSingleNode("myns:Cars", nsMgr);
    Console.WriteLine(node.OuterXml);
    var carSerializer = new XmlSerializer(typeof(Car));
    using (var reader = new XmlNodeReader(node))
    {
        // What I want is a list of Car instances deserialized from
        // the Car child elements of the Cars element.
        // The following line throws an InvalidOperationException
        // "<Cars xmlns:'http://MyNamespace' /> was not expected"
        // If I change SelectSingleNode above to select "myns:Cars/myns:Car"
        // I get "<Car xmlns:'http://MyNamespace' /> was not expected"
        var result = carSerializer.Deserialize(reader);
    }
}

我还想随后更新我的 Car class 实例,并使用 XmlSerializer 将其重新插入到文档中,这是后续问题的主题 如何使用XmlSerializer在大文档中插入节点 .

xsd 和生成的 class 如下:

<xs:schema xmlns="http://MyNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           targetNamespace="http://MyNamespace" 
           elementFormDefault="qualified" attributeFormDefault="unqualified" 
           version="3.9.0.8">
  <xs:complexType name="Cars">
    <xs:sequence>
      <xs:element name="Car" type="Car" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="Car">
    <xs:attribute name="make" type="xs:string" use="required"/>
  </xs:complexType>
  <xs:complexType name="RootNode">
    <xs:sequence>
      <xs:element name="Cars" type="Cars" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
  <xs:element name="RootNode" type="RootNode" />
</xs:schema>

代码由xsd.exe生成:

using System.Xml.Serialization;


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://MyNamespace")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://MyNamespace", IsNullable=false)]
public partial class RootNode {

    private Car[] carsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)]
    public Car[] Cars {
        get {
            return this.carsField;
        }
        set {
            this.carsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://MyNamespace")]
public partial class Car {

    private string makeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string make {
        get {
            return this.makeField;
        }
        set {
            this.makeField = value;
        }
    }
}

你这里有两个问题:

  1. var node = doc.DocumentElement.SelectSingleNode("myns:Cars", nsMgr); 位于 <Cars> 元素——<Car> 节点重复序列的容器元素——但是你的 XmlSerializer 被构造为反序列化名为 <Car> 的单个根元素。尝试使用为反序列化单个汽车而构造的序列化程序来反序列化一系列汽车是行不通的。

  2. 出于某种原因 xsd.exe 为您的 Car 类型生成了一个没有 XmlRoot 属性的定义:

    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://MyNamespace")]
    // Not included!
    //[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://MyNamespace")]
    public partial class Car
    {
    }
    

    因此,如果您尝试将 Car 的单个实例序列化或反序列化为 XML 文档 的根 XML 元素那么 XmlSerializer 将期望该根元素不在任何名称空间中。大型文档中的每个 <Car> 节点都在 "http://MyNamespace" 默认命名空间中,因此尝试单独反序列化每个节点也是行不通的。

    您可以手动将缺少的 [XmlRoot(Namespace = "http://MyNamespace")] 属性添加到 Car,但如果 XSD 文件随后被修改并且 c# 类型需要重生。

为避免这两个问题,您可以将 XmlNode.SelectNodes(String, XmlNamespaceManager) to select every <Car> nodes inside the <Cars> element, then deserialize each one by constructing an XmlSerializer 与要反序列化的节点的元素名称和名称空间的覆盖 XmlRootAttribute 一起使用。首先,定义如下扩展方法:

public static partial class XmlNodeExtensions
{
    public static List<T> DeserializeList<T>(this XmlNodeList nodes)
    {
        return nodes.Cast<XmlNode>().Select(n => n.Deserialize<T>()).ToList();
    }

    public static T Deserialize<T>(this XmlNode node)
    {
        if (node == null)
            return default(T);
        var serializer = XmlSerializerFactory.Create(typeof(T), node.LocalName, node.NamespaceURI);
        using (var reader = new XmlNodeReader(node))
        {
            return (T)serializer.Deserialize(reader);
        }
    }
}

public static class XmlSerializerFactory
{
    // To avoid a memory leak the serializer must be cached.
    // 
    // This factory taken from 
    // 

    readonly static Dictionary<Tuple<Type, string, string>, XmlSerializer> cache;
    readonly static object padlock;

    static XmlSerializerFactory()
    {
        padlock = new object();
        cache = new Dictionary<Tuple<Type, string, string>, XmlSerializer>();
    }

    public static XmlSerializer Create(Type serializedType, string rootName, string rootNamespace)
    {
        if (serializedType == null)
            throw new ArgumentNullException();
        if (rootName == null && rootNamespace == null)
            return new XmlSerializer(serializedType);
        lock (padlock)
        {
            XmlSerializer serializer;
            var key = Tuple.Create(serializedType, rootName, rootNamespace);
            if (!cache.TryGetValue(key, out serializer))
                cache[key] = serializer = new XmlSerializer(serializedType, new XmlRootAttribute { ElementName = rootName, Namespace = rootNamespace });
            return serializer;
        }
    }
}

然后反序列化如下:

var nodes = doc.DocumentElement.SelectNodes("myns:Cars/myns:Car", nsMgr);
var cars = nodes.DeserializeList<Car>();

必须缓存使用覆盖根元素名称或命名空间构造的序列化程序的节点,以避免内存泄漏,如 this answer by Marc Gravell 中所述。

工作示例 .Net fiddle